#include <stdio.h>
#include <stdlib.h>

int vis[10][10] = {0};
int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int orangesRotting(int **grid, int gridSize, int *gridColSize)
{
    int que[100][2], t[2];
    int r = 0, f = 0, sum = -1, c1 = 0, c2 = 0;
    for (int i = 0; i < gridSize; i++)
        for (int j = 0; j < gridColSize[0]; j++)
        {
            if (grid[i][j] == 2)
            {
                que[r][0] = i;
                que[r++][1] = j;
                c1++;
            }
        }
    while (f < r)
    {
        t[0] = que[f][0];
        t[1] = que[f++][1];
        c1--;
        for (int i = 0; i < 4; i++)
        {
            int nx, ny;
            nx = t[0] + dir[i][0];
            ny = t[1] + dir[i][1];
            if (nx >= 0 && nx < gridSize && ny >= 0 && ny < gridColSize[0])
            {
                if (grid[nx][ny] == 1)
                {
                    grid[nx][ny] = 2;
                    que[r][0] = nx;
                    que[r++][1] = ny;
                    c2++;
                }
            }
        }
        if (c1 == 0)
        {
            sum++;
            c1 = c2;
            c2 = 0;
        }
    }
    if (sum == -1)
        return -1;
    return sum + 1;
}

int main()
{
    /*******************code*******************/
    //[[2,1,1],[1,1,0],[0,1,1]]
    int a[][3] = {{2, 1, 1}, {1, 1, 0}, {0, 1, 1}};
    int **p = (int **)malloc(sizeof(int *) * 3);
    for (int i = 0; i < 3; i++)
    {
        p[i] = a[i];
    }
    int l[3] = {3, 3, 3};
    int m = orangesRotting(p, 3, l);
    /******************************************/
    fflush(stdin);

    printf("\n\n****************************\n");
    printf("Press Enter key to continue\n");
    getchar();
    return 0;
    /******************************************/
}
